<template>
  <el-form label-width="auto" style="max-width: 600px">
    <el-form-item label="请输入消息">
      <el-input v-model="messageText.content" type="textarea" />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="sendMsg()">发送</el-button>
      <el-button type="danger" @click="disableWebSocket()">断开连接</el-button>
      <el-button type="success" @click="initWebSocket()">重新连接</el-button>
    </el-form-item>
  </el-form>
</template>

<script setup>
import {onBeforeUnmount, onMounted, reactive, ref} from "vue";

let messageText = reactive({
  from: 1,
  to: 2,
  type: 0,
  groupId: null,
  content: ''
})

let receiveMsg = reactive({
  from: null,
  to: null,
  type: null,
  groupId: null,
  content: null
})

let websocket = null

const initWebSocket = () => {
  websocket = new WebSocket('ws://localhost:8004/webrtc');
  websocket.onopen = webSocketOnOpen
  websocket.onmessage = webSocketOnMessage
  websocket.onclose = webSocketOnClose
  websocket.onerror = webSocketOnError
}

const webSocketOnOpen = (event) => {
  console.log('建立连接')
  sendLoginMsg();
}

const webSocketOnMessage = (event) => {
  Object.assign(receiveMsg, JSON.parse(event.data))
  console.info("收到消息：" + receiveMsg.content);
}

const webSocketOnClose = (event) => {
  console.error('连接关闭');
}

const webSocketOnError = (event) => {
  console.error('连接错误');
}

const sendMsg = () => {
  messageText.type = 1
  websocket.send(JSON.stringify(messageText))
  console.info('发送消息：' + messageText.content)
}

const sendLoginMsg = () => {
  websocket.send(JSON.stringify(messageText))
}

const disableWebSocket = () => {
  messageText.type = -1
  messageText.content = null;
  websocket.send(JSON.stringify(messageText))
  websocket.close()
}

onMounted(() => {
  initWebSocket()
})

onBeforeUnmount(() => {
  disableWebSocket()
})
</script>

<style scoped>
.homepage-hero-module,
.video-container {
  position: relative;
  height: 100vh;
  overflow: hidden;
}

.video-container .poster img {
  z-index: 0;
  position: absolute;
}

.video-container .filter {
  z-index: 1;
  position: absolute;
  /*background: rgba(0, 0, 0, 0.4);*/
  width: 100%;
}

.fillWidth {
  width: 100%;
}
</style>
